<template>
  <div class="upload-file">
    <!-- 原生文件上传区域 -->
    <div class="upload-area" @click="triggerFileInput" @dragover.prevent="dragover" @drop.prevent="drop">
      <input type="file" ref="fileInput" @change="handleFileChange" style="display:none" accept=".mp4,.3gp,.jpg,.jpeg,.png" multiple/>
      <div class="upload-content">
        <i class="el-icon-upload"></i>
        <div class="upload-text">{{ $t('fileUpload.dragAndDrop') }}<em>{{ $t('fileUpload.clickToUpload') }}</em></div>
        <div v-if="showTip" class="upload-tip">{{ $t('fileUpload.uploadTip', { fileSize: fileSize }) }}</div>
      </div>
    </div>
    <!-- 文件列表 - 修改为缩略图平铺 -->
    <transition-group class="upload-file-list thumbnail-list" name="el-fade-in-linear" tag="div">
      <div :key="file.uid" class="thumbnail-item" v-for="(file, index) in fileList">
        <el-link :href="`${baseUrl}${file.url}`" :underline="false" target="_blank">
          <div class="thumbnail-content">
            <img v-if="isImage(file.name)" :src="`${baseUrl}${file.url}`" class="thumbnail-image" alt="">
            <div v-else class="thumbnail-icon">
              <i :class="getFileIcon(file.name)"></i>
            </div>
            <span class="thumbnail-name">{{ getFileName(file.name) }}</span>
          </div>
        </el-link>
        <div class="thumbnail-actions">
          <el-link :underline="false" @click="handleDelete(index)" type="danger" class="delete-btn">{{ $t('common.delete') }}</el-link>
          <el-progress v-if="file.uploading" :percentage="file.progress||0" :stroke-width="2" style="width:100%;margin-top:5px;"/>
        </div>
      </div>
    </transition-group>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import request from '@/utils/request'

export default {
  name: "FileUpload",
  props: {
    // 值
    value: [String, Object, Array],
    // 数量限制
    limit: {
      type: Number,
      default: 5,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 500,
    },
    isShowTip: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      fileList: [],
      isDragging: false
    };
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          let temp = 1;
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : this.value.split(',');
          // 然后将数组转为对象数组
          this.fileList = list.map(item => {
            if (typeof item === "string") {
              item = { name: item, url: item };
            }
            item.uid = item.uid || new Date().getTime() + temp++;
            return item;
          });
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    showTip() {
      return this.isShowTip && (this.fileSize);
    },
  },
  methods: {
    triggerFileInput() {
      this.$refs.fileInput.click();
    },
    handleFileChange(e) {
      const files = Array.from(e.target.files);
      this.processFiles(files);
      e.target.value = '';
    },
    // 处理拖拽上传
    dragover(e) {
      this.isDragging = true;
      e.dataTransfer.dropEffect = 'copy';
    },
    // 处理拖放
    drop(e) {
      this.isDragging = false;
      const files = Array.from(e.dataTransfer.files);
      this.processFiles(files);
    },
    // 处理文件上传前的验证和准备
    processFiles(files) {
      if (files.length === 0) return;

      for (let i = 0; i < files.length; i++) {
        const file = files[i];
        const fileExtension = file.name.lastIndexOf(".") > -1 ?
          file.name.slice(file.name.lastIndexOf(".") + 1).toLowerCase() : '';

        // 检查文件类型
        if (!['jpg', 'jpeg', 'png', 'mp4', '3gp'].includes(fileExtension)) {
          this.$message.error(this.$t('fileUpload.fileTypeError'));
          return;
        }

        // 检查文件大小
        if (this.fileSize && (file.size / 1024 / 1024 > this.fileSize)) {
          this.$message.error(this.$t('fileUpload.fileSizeError', { fileSize: this.fileSize }));
          return;
        }
      }
      this.uploadFiles(files);
    },
    uploadFiles(files) {
      console.log('uploadFiles:', files);
      const formData = new FormData();
      files.forEach(file => {
        formData.append('files', file);
        const uid = new Date().getTime() + Math.random().toString(36).substr(2, 5);
        this.fileList.push({uid, name: file.name, uploading: true, progress: 0});
      });

      console.log('formData:', formData.getAll('files'));

      const loadingMessage = this.$message({
        message: `<strong style="color: #f56c6c; font-weight: bold;">${this.$t('fileUpload.uploading')}</strong>`,
        type: 'info',
        duration: 0, // 设置为0表示不会自动关闭
        showClose: true,
        dangerouslyUseHTMLString: true
      });

      request({
        url: '/iot/tool/upload',
        method: 'post',
        data: formData,
        headers: {'Content-Type': 'application/json'}
      }).then(response => {
        // 上传完成后将所有正在上传的文件进度设为100%
        this.fileList.forEach(file => {
          if (file.uploading) {
            file.progress = 100;
          }
        });
        loadingMessage.close();
        // 稍等片刻让用户看到100%进度
        setTimeout(() => {
          this.handleUploadSuccess(response, files);
        }, 300);
      }).catch(error => {
        loadingMessage.close();
        this.handleUploadError(error.message);
      });
    },
    updateFileProgress(uid, progress) {
      const fileIndex = this.fileList.findIndex(file => file.uid === uid);
      if (fileIndex !== -1) {
        this.$set(this.fileList[fileIndex], 'progress', progress);
      }
    },
    handleUploadSuccess(res, files) {
      console.log('res:', res);
      this.$message.success(this.$t('fileUpload.uploadSuccess'));

      // 获取所有正在上传的文件
      const uploadingFiles = this.fileList.filter(f => f.uploading);

      // 处理后端响应
      if (Array.isArray(res.urls)) {
        // 多文件上传情况
        res.urls.forEach((url, index) => {
          if (uploadingFiles[index]) {
            uploadingFiles[index].url = url;
            uploadingFiles[index].uploading = false;
            uploadingFiles[index].progress = 100;
          }
        });
      } else if (res.url) {
        // 单文件上传情况（兼容处理）
        if (uploadingFiles[0]) {
          uploadingFiles[0].url = res.url;
          uploadingFiles[0].uploading = false;
          uploadingFiles[0].progress = 100;
        }
      }
      this.$emit("input", this.listToString(this.fileList));
    },
    // 上传失败处理
    handleUploadError(err) {
      this.$message.error(this.$t('fileUpload.uploadFailed') + (err || this.$t('fileUpload.pleaseRetry')));
      // 移除所有正在上传的文件
      this.fileList = this.fileList.filter(f => !f.uploading);
    },
    // 删除文件
    handleDelete(index) {
      this.fileList.splice(index, 1);
      this.$emit("input", this.listToString(this.fileList));
    },
    // 获取文件名称
    getFileName(name) {
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1).toLowerCase();
      } else {
        return name;
      }
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].url + separator;
      }
      return strs != '' ? strs.substr(0, strs.length - 1) : '';
    },
    isImage(filename) {
      const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
      const extension = filename.split('.').pop().toLowerCase();
      return imageExtensions.includes(extension);
    },
    // 获取文件类型对应的图标
    getFileIcon(filename) {
      const extension = filename.split('.').pop().toLowerCase();
      const iconMap = {
        pdf: 'el-icon-document',
        doc: 'el-icon-document',
        docx: 'el-icon-document',
        xls: 'el-icon-document',
        xlsx: 'el-icon-document',
        ppt: 'el-icon-document',
        pptx: 'el-icon-document',
        txt: 'el-icon-document',
        zip: 'el-icon-folder',
        rar: 'el-icon-folder',
        '7z': 'el-icon-folder',
        mp3: 'el-icon-headset',
        mp4: 'el-icon-video-camera',
        mov: 'el-icon-video-camera',
        avi: 'el-icon-video-camera',
        '3gp': 'el-icon-video-camera'
      };
      return iconMap[extension] || 'el-icon-document';
    }
  }
};
</script>

<style scoped lang="scss">
.upload-file {
  .upload-area {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    padding: 20px;
    text-align: center;
    transition: border-color 0.3s;
    background-color: #fafafa;
    &:hover {
      border-color: #409EFF;
    }
    .upload-content {
      .el-icon-upload {
        font-size: 67px;
        color: #c0c4cc;
        margin-bottom: 16px;
      }
      .upload-text {
        color: #606266;
        font-size: 14px;
        em {
          color: #409EFF;
          font-style: normal;
        }
      }
      .upload-tip {
        color: #909399;
        font-size: 12px;
        margin-top: 7px;
      }
    }
  }
}
/* 文件列表样式 */
.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}
.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}
.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}
/* 缩略图网格布局 */
.thumbnail-list {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  margin-top: 16px;
}
.thumbnail-item {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 8px;
  display: flex;
  flex-direction: column;
  height: 100%;
}
.thumbnail-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  flex-grow: 1;
}
.thumbnail-image {
  max-width: 100%;
  height: auto;
  max-height: 100px;
  object-fit: contain;
}
.thumbnail-icon {
  font-size: 48px;
  color: #409EFF;
  margin-bottom: 8px;
}
.thumbnail-name {
  display: block;
  width: 100%;
  text-align: center;
  word-break: break-all;
  margin-top: 8px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  min-height: 40px;
  line-height: 1.2;
  padding: 0 4px;
  box-sizing: border-box;
}
.thumbnail-actions {
  margin-top: auto;
  padding-top: 2px;
  width: 100%;
  text-align: center;
}
.delete-btn {
  display: inline-block;
  width: 100%;
  text-align: center;
  padding: 6px 0;
  line-height: 1;
  background-color: #fef0f0;
  border-radius: 4px;
  transition: background-color 0.3s;
  color: #f56c6c;
  font-size: 14px;
  &:hover {
    background-color: #fde2e2;
    color: #f56c6c;
  }
  &.el-link--danger {
    color: #f56c6c;
    &:hover {
      color: #f56c6c;
    }
  }
}
</style>
